from . import mon_bp
from flask import render_template,jsonify,make_response,request
from flask_restful import Api,Resource
from model.monitor import mem_t
from lib.response import response
from mail.mail_warn import warn
from model.user import host

api = Api(mon_bp)

class mem(Resource):
    def get(self,id = None):
        if id is None:
            result = mem_t.get()
        else:
            result = mem_t.get_by_id(id)
        result = response(data=result, message="get disk innfo success")
        # return result
        return make_response(render_template('mem_monitor.html',data = result),200)
    def post(self):
        hostname = request.json.get("hostname")
        date = request.json.get("date")
        used = request.json.get("used")
        free = request.json.get("free")
        total = request.json.get("total")
        used_percent = request.json.get("used_percent")

        mem_t.create(hostname,date,used,free,total,used_percent)
        email_t = host.query.filter_by(hostname=hostname).first().user_info.email
        warn.mem_warn(used_percent,hostname,email_t)
        return response(message="create disk innfo success")
    def put(self,id):
        hostname = request.json.get("hostname")
        date = request.json.get("date")
        used = request.json.get("used")
        free = request.json.get("free")
        total = request.json.get("total")
        used_percent = request.json.get("used_percent")

        mem_t.update(id, hostname, date, used, free, total, used_percent)
        return response(message="update disk innfo success")
    def delete(self,id):
        mem_t.delete(id)
        return response(message="delete disk_info success")

api.add_resource(mem,'/mem')
api.add_resource(mem,'/mem/<int:id>',endpoint='memid')
